import dayjs from "dayjs";
import Link from "next/link";
import relativeTime from "dayjs/plugin/relativeTime";

import { $api } from "~/shared/api";
import { Card } from "~/shared/ui/card";
import { Avatar, AvatarImage } from "~/shared/ui/avatar";
import { convertEmoji } from "~/shared/lib/convert-emoji";

import { RefreshButton } from "./_components/refresh-form";
import { AutoUpdatedDate } from "./_components/auto-updated-date";

dayjs.extend(relativeTime);

export default async function Home() {
  const data = await $api.rest.repos.listCommits({
    owner: "velenyx",
    repo: "github-commit-explorer",
  });

  return (
    <div className="container">
      <h1 className="mt-8 text-center text-6xl font-semibold">
        <span className="text-blue-700">There are</span> {data.data.length}{" "}
        commits!
      </h1>
      <RefreshButton />
      <div className="mt-10">
        {data.data.map((commit) => (
          <Link key={"link" + commit.sha} href={`/sha/${commit.sha}`}>
            <Card
              key={commit.sha}
              className="mt-4 cursor-pointer p-5 transition-all hover:border-blue-400 hover:text-blue-400"
            >
              <h2 className="text-2xl">
                {convertEmoji(commit.commit.message)}
              </h2>
              <div className="mt-3 flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <span className="text-lg">by</span>
                  <Avatar>
                    <AvatarImage src={commit.author?.avatar_url} />
                  </Avatar>
                  <span className="text-lg">{commit.commit.author?.name}</span>
                </div>
                <AutoUpdatedDate
                  date={commit.commit.committer?.date || dayjs().toString()}
                />
              </div>
            </Card>
          </Link>
        ))}
      </div>
    </div>
  );
}
